package system.task.logger.buffer;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TaskLogBufferAdmin {

    public static TaskLogBufferAdmin instance = new TaskLogBufferAdmin();

    private final Map<String, TaskLogBuffer> map = new ConcurrentHashMap<>();

    private TaskLogBufferAdmin() {

    }

    public void log(int maxLine, String taskName, String runId, String content) {
        TaskLogBuffer logBuffer = this.map.get(taskName);
        if (logBuffer == null) {
            synchronized (this.map) {
                logBuffer = this.map.get(taskName);
                if (logBuffer == null) {
                    logBuffer = new TaskLogBuffer(maxLine, taskName);
                    this.map.put(taskName, logBuffer);
                }
            }
        }
        logBuffer.log(runId, content);
    }

    public List<TaskLogBufferItem> list(String name, int lastIndex) {
        TaskLogBuffer logBuffer = this.map.get(name);
        if (logBuffer != null) {
            return logBuffer.list(lastIndex);
        }
        return Collections.EMPTY_LIST;
    }
}
